import { DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import { type ProColumns, ProTable } from '@ant-design/pro-components';
import { Button, Col, Form, Input, Modal, message, Row } from 'antd';
import { useEffect, useRef, useState } from 'react';
import PopconfirmButton from '@/components/PopconfirmButton';
import { getAuthUserAllocatedList } from '@/services/ant-design-pro/api';
import {
  cancelAuthAllUser,
  cancelAuthUser,
  getRoleInfo,
} from '@/services/role';
import AddUsers from './AddUsers';

type Props = {
  roleId: any;
  onOk?: () => void;
  onClose?: (reflash?: boolean) => void;
};
const App = (props: Props) => {
  const { roleId, onOk = () => {}, onClose = () => {} } = props;
  const [open, setOpen] = useState<boolean>(false);
  const [form] = Form.useForm();
  const [pageNum, setPageNum] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(10);
  const myTableRef = useRef<any>(null);

  const cancel = async (userIds: string, isMultiple: boolean) => {
    const { success } = isMultiple
      ? await cancelAuthAllUser({
          roleId,
          userIds: userIds,
        })
      : await cancelAuthUser({
          roleId,
          userId: userIds,
        });
    if (success) {
      message.success('取消成功');
      myTableRef.current?.reload();
    }
  };
  const columns: ProColumns<Record<string, any>, 'text'>[] | undefined = [
    {
      title: '员工代码',
      dataIndex: 'userName',
      key: 'userName',
    },
    {
      title: '员工姓名',
      dataIndex: 'nickName',
      key: 'nickName',
      search: false,
    },
    //emial
    // {
    //   title: "用户邮箱",
    //   dataIndex: "email",
    //   key: "email",
    //   search: false,
    // },
    {
      title: '手机号',
      dataIndex: 'phonenumber',
      key: 'phonenumber',
    },
    //status
    // {
    //   title: "状态",
    //   dataIndex: "status",
    //   key: "status",
    //   search: false,
    //   render: (_: any, record: any) => {
    //     return record.status === "0" ? (
    //       <Tag color="green">正常</Tag>
    //     ) : (
    //       <Tag color="red">停用</Tag>
    //     );
    //   },
    // },
    //create time
    // {
    //   title: "创建时间",
    //   dataIndex: "createTime",
    //   key: "createTime",
    //   search: false,
    // },
    //操作
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <PopconfirmButton
          size="small"
          type="link"
          key={'cancel'}
          danger={false}
          title={`确定删除 " ${record.nickName} " 吗？`}
          icon={<DeleteOutlined />}
          onConfirm={() => {
            cancel(record.userId, false);
          }}
        >
          删除
        </PopconfirmButton>,
      ],
    },
  ];
  // const rowSelection: TableProps<Record<string, any>>["rowSelection"] = {
  //   onChange: (
  //     selectedRowKeys: React.Key[],
  //     selectedRows: Record<string, any>[]
  //   ) => {
  //     console.log(
  //       `selectedRowKeys: ${selectedRowKeys}`,
  //       "selectedRows: ",
  //       selectedRows
  //     );
  //     setSelectedRowKeys(selectedRowKeys);
  //     setSelectedRows(selectedRows);
  //   },
  //   getCheckboxProps: (record: any) => ({
  //     disabled: record.admin, // Column configuration not to be checked
  //   }),
  // };
  useEffect(() => {
    (async () => {
      const { data } = await getRoleInfo(roleId);
      const { remark, roleKey, roleName } = data || {};
      form.setFieldsValue({ roleName, roleKey, remark });
      console.log('role info data', roleKey, data);
    })();
  }, []);
  return (
    <Modal
      open
      width={800}
      title="人员配置"
      onCancel={() => {
        onClose();
      }}
      okText="关闭"
      onOk={onOk}
      cancelButtonProps={{
        style: {
          display: 'none',
        },
      }}
    >
      <Form
        form={form}
        labelCol={{
          span: 8,
        }}
      >
        <Row>
          <Col span={8}>
            <Form.Item label="角色代码" name="roleKey">
              <Input disabled placeholder="角色代码" />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="角色名称" name="roleName">
              <Input disabled placeholder="角色名称" />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="备注" name="remark">
              <Input disabled placeholder="备注" />
            </Form.Item>
          </Col>
        </Row>
      </Form>

      <ProTable
        actionRef={myTableRef}
        scroll={{
          y: 250,
        }}
        // rowSelection={rowSelection}
        search={false}
        columns={columns}
        toolBarRender={() => {
          return [
            <Button
              key={'add'}
              size="small"
              onClick={() => {
                setOpen(true);
              }}
              type="primary"
              ghost
              icon={<PlusOutlined />}
            >
              添加人员
            </Button>,
            //
            // <PopconfirmButton
            //   icon={<CheckCircleOutlined />}
            //   disabled={selectedRowKeys.length === 0}
            //   title={`确定要取消${selectedRows
            //     .map((row) => row.userName)
            //     .join(",")}吗？`}
            //   onConfirm={() => {
            //     cancel(selectedRowKeys?.join(","), true);
            //   }}
            // >
            //   批量取消授权
            // </PopconfirmButton>,
            // <Button
            //   icon={<CloseCircleOutlined />}
            //   onClick={() => {
            //     history.push("/system/role");
            //   }}
            // >
            //   关闭
            // </Button>,
          ];
        }}
        request={async (params) => {
          const { rows, total, success } = await getAuthUserAllocatedList({
            roleId,
            pageNum,
            pageSize,
            ...params,
          });
          return {
            data: rows,
            total,
            success,
          };
        }}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          pageSize,
          current: pageNum,
          onChange: (page, size) => {
            setPageNum(page);
            setPageSize(size);
          },
        }}
        rowKey="userId"
      />

      {open ? (
        <AddUsers
          roleId={roleId}
          onClose={(reflash) => {
            setOpen(false);
            if (reflash) {
              myTableRef.current?.reload();
            }
          }}
        />
      ) : null}
    </Modal>
  );
};
export default App;
